package com.genersoft.iot.vmp.conf;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.genersoft.iot.vmp.storager.impl.RedisCatchStorageImpl;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import javax.sql.DataSource;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 配置mybatis
 */
@Configuration
@Order(value=1)
public class MybatisConfig {
    private final Logger logger = LoggerFactory.getLogger(RedisCatchStorageImpl.class);
    @Autowired
    private UserSetting userSetting;

    @Bean
    public DatabaseIdProvider databaseIdProvider() {
        VendorDatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
        Properties properties = new Properties();
        properties.setProperty("Oracle", "oracle");
        properties.setProperty("MySQL", "mysql");
        properties.setProperty("DB2", "db2");
        properties.setProperty("Derby", "derby");
        properties.setProperty("H2", "h2");
        properties.setProperty("HSQL", "hsql");
        properties.setProperty("Informix", "informix");
        properties.setProperty("MS-SQL", "ms-sql");
        properties.setProperty("PostgreSQL", "postgresql");
        properties.setProperty("Sybase", "sybase");
        properties.setProperty("Hana", "hana");
        properties.setProperty("DM", "dm");
        properties.setProperty("KingbaseES", "kingbase");
        properties.setProperty("KingBase8", "kingbase");
        databaseIdProvider.setProperties(properties);
        return databaseIdProvider;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource, DatabaseIdProvider databaseIdProvider) throws Exception {
       final SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
        if (userSetting.getSqlLog()) {
            config.setLogImpl(StdOutImpl.class);
        }
        config.setMapUnderscoreToCamelCase(true);
        sqlSessionFactory.setConfiguration(config);
        sqlSessionFactory.setDatabaseIdProvider(databaseIdProvider);
        initDb(dataSource);
        return sqlSessionFactory.getObject();
    }

    private void initDb(DataSource dataSource) {
        InputStream in = this.getClass().getResourceAsStream("/init.sql");
        String line = IoUtil.read(in, Charset.forName("utf-8"));
        String[] values = line.split(";");
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            for (String s : values) {
                if (StrUtil.isBlank(s)) {
                    continue;
                }
                PreparedStatement ps = null;
                try {
                    connection.setAutoCommit(false);
                    ps = connection.prepareStatement(s);
                    ps.execute();
                    connection.commit();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                } finally {
                    IoUtil.close(ps);
                }
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            IoUtil.close(connection);
        }
    }
}
